import 'package:core/core.dart';
import 'package:permission_handler/permission_handler.dart';

/// @author zdl
/// date 2021/1/4 19:46
/// email zdl328465042@163.com
/// description 权限工具类
class PermissionHelper {
  const PermissionHelper._();

  /// 存储权限
  static Future<bool> hasStorage({Function? function}) => _apply(Permission.storage, function);

  /// 相机权限
  static Future<bool> hasCamera({Function? function}) => _apply(Permission.camera, function);

  /// 定位权限
  static Future<bool> hasLocation({Function? function}) => _apply(Permission.location, function);

  /// 定位权限
  static Future<bool> locationAlways({Function? function}) => _apply(Permission.locationAlways, function);

  /// 麦克风权限
  static Future<bool> hasAudio({Function? function}) => _apply(Permission.microphone, function);

  /// 蓝牙权限
  static Future<bool> hasBluetooth({Function? function}) => _apply(Permission.bluetooth, function);

  /// 蓝牙权限
  static Future<bool> hasBluetoothAdvertise({Function? function}) => _apply(Permission.bluetoothAdvertise, function);

  /// 蓝牙权限
  static Future<bool> hasBluetoothScan({Function? function}) => _apply(Permission.bluetoothScan, function);

  /// 蓝牙权限
  static Future<bool> hasBluetoothConnect({Function? function}) => _apply(Permission.bluetoothConnect, function);

  /// 申请
  static Future<bool> _apply(Permission permission, Function? function) async {
    bool result = false;
    var status = await permission.status;
    switch (status) {
    //同意
      case PermissionStatus.granted:
        result = true;
    //拒绝
      case PermissionStatus.denied:
      //不确定的
      // case PermissionStatus.undetermined:
        result = await permission.request() == PermissionStatus.granted;
    //Android拒绝且不再提示
      case PermissionStatus.permanentlyDenied:
      //ios拒绝且不再提示
      case PermissionStatus.restricted:
        await openAppSettings();
        result = false;
      default:
        result = false;
    }
    LogHelper.d(result ? '有权限' : '无权限', title: '${permission.toString()}状态');
    if(result == true) function?.call();
    return result;
  }
}
